<template>
	<view>
		<image src="../../static/avatar.png" class="logo" mode="widthFix"></image>
		<view class="cu-bar search">
			<yuan ref="yuans" @flags="flag"></yuan>
			<view class="search-form round bg-white">
				<text class="cuIcon-search"></text>
				<input :adjust-position="false" type="text" @input='searchKey' :placeholder="placeholder"
					confirm-type="search" :value="key" @confirm="searchBtn(0)" ></input>
			</view>
			<view class="">
				<text @click="searchBtn(0)" style="font-size: 40rpx;margin-right: 20rpx;">{{$t('guize.listtab2')}}</text>
			</view>
		</view>

		<view class="jilu" >
			<view class="jilist">
				<p class="font-weght">{{$t('search.lishi')}}</p>
				<p style="right:0; display: block;position: absolute;margin-right:30rpx" @click="del" v-if="jiludata.length>0">
					{{$t('search.qk')}}
				</p>
			</view>
			<!-- <text v-for="(item,index) in jiludata" :key="index" class="sotext" @click="searchBtn(item)">{{item}}</text> -->
			<view style="height: 400rpx;display: block;" v-if="jiludata.length>0">
			<qiun-data-charts type="word" :opts="opts" :chartData="chartData" @getIndex="getIndex" v-if="FontFace" />
			</view>
			<view style="height: 400rpx;display: block;text-align: center;" v-else>
				<!-- <view class="iconfont" style="font-size: 130rpx;margin-top: 50rpx;" >&#xe605;</view>
			<view>没有数据哦~</view> -->
			<image src="../../static/no.png" mode="widthFix" style="width:200rpx"></image>
			</view>
		</view>
		
		<view class="margin-top text-center" v-if="sqllist.length <= 0">
			{{$t('search.wjcdxs')}}
			<font style="color:red" @click="ge()">{{$t('search.pzgz')}}</font>
		</view>

		<wyb-popup ref="popup" type="bottom" radius="6" :showCloseIcon="false" :scrollY="true" height="800" @hide="popup" >
		
			<view class="cu-bar">
				<view class="action ">
					<text>{{$t('search.ssjg')}}:({{key}})</text>
				</view>
				<text class="stop iconfont" @click="stops()" v-if="pageLoading">&#xea89; {{$t('search.tz')}}</text>
			</view>
			<ls-loading :text="$t('search.ssz')" :animation="animation" v-if="pageLoading" :embed="true"
				style="margin-bottom: 20rpx;display: block;"></ls-loading>
			<scroll-view  class="head-hight popup-content" :scroll-y="true">
				<view class="cu-list menu-avatar" v-if="listDatas.length > 0">
					<view class="cu-item lh" v-for="(item,index) in listDatas" :key="index"
						@click="details(item,item.id)">
						<image :src="item.img" class="cu-avatar radius xl" mode="widthFix"></image>
						<view class="content">
							<view>
								<view class="text-cut">{{item.name}}</view>
								<view class="cu-tag round bg-orange sm" v-show="item.author">{{item.author}}</view>
							</view>
							<view class="text-gray text-sm flex" v-if="item.sort">

								<view class="text-cut">{{item.sort}}</view>
							</view>
							<view class="text-gray text-sm flex" v-if="item.chapter">

								<view class="text-cut">{{item.chapter}}</view>
							</view>
							<view class="text-gray text-sm flex">

								<view class="text-cut">{{item.introduce}}</view>
							</view>
						</view>
						<view class="cu-tag round bg-orange sm">网页来源{{item.list.length?item.list.length:1}}条</view>
					</view>

				</view>
				<view v-else>
					<view class="margin-top text-center" v-if="sqllist.length === (solimit+1) && key">
						{{$t('search.my')}}
						<font style="color:red" @click="ge()">{{$t('search.dw')}}</font>
					</view>
				</view>
			</scroll-view>
			
		</wyb-popup>
	
		<view class="pointer-bottom">
			<text class="font-weght"></text>
			<text class="margin-right" @click="nexturl(config.book_source_yuan)">📋使用说明</text>
			<text class="margin-right">　　　　</text>
			<text class="margin-right" @click="nexturl(config.book_source_list)">⚜️畅读说明</text>
		</view>
		<view v-if="config.c_ad && adtype">
			<gr-ad :data="config" :type="adtype" :height="150" ref="adad"></gr-ad>
		</view>
	
 <custom-tab-bar :currentTab="currentTab"></custom-tab-bar>
	</view>
</template>

<script>
	import _tool from '@/util/tools.js';
	import _pc from '@/util/pc.js';
	// #ifdef  APP-PLUS
	import _sql from '@/util/sql.js';
	// #endif
	import customTabBar from '@/components/customTabBar.vue';
	export default {
		components: {
		    customTabBar
		  },
		data() {
			return {
				currentTab:'/pages/book_mall/index',
				concurrencyLimit:3,
				executingCount :0,
				linkQueue :[],
				isurl:false,
				url:false,
				key: '',
				FontFace:false,
				placeholder: '这里输入书名或作者名称',
				listData: [],
				sqllist: [],
				listDatas: [],
				timer: [],
				pageLoading: false,
				animation: 'twinkle',
				jiludata: [],
				solimit: 0,
				sum: 0,
				adtype:0,
				config:{},
				chartData: {},
				//您可以通过修改 config-ucharts.js 文件中下标为 ['word'] 的节点来配置全局默认参数，如都是默认参数，此处可以不传 opts 。实际应用过程中 opts 只需传入与全局默认参数中不一致的【某一个属性】即可实现同类型的图表显示不同的样式，达到页面简洁的需求。
				opts: {
					color: ["#1890FF", "#91CB74", "#FAC858", "#EE6666", "#73C0DE", "#3CA272", "#FC8452", "#9A60B4",
						"#ea7ccc"
					],
					padding: undefined,
					extra: {
						word: {
							type: "normal",
							autoColors: true
						}
					}
				}
			}
		},
		onShow() {
			uni.setStorageSync('adis',0)
			_pc.system()
			this.batchSize=3,
			this.currentIndex =0,
			this.$nextTick(() => {
				this.$refs.popup.close();
			})
			this.stops()
			var _this = this;
			//clearInterval(_this.timer)
			// #ifdef  APP-PLUS
			_sql.selectSQL("select * from " + this.dbs + " where book_state=1").then(function(res) {
				_this.sqllist = res
			});
			// #endif
			// #ifdef  MP
			this.get(this.Httpus + '/index.php?s=Home-Ad-config')
			_this.sqllist = uni.getStorageSync('shuyuan1')
			// #endif

			console.log(' _this.sqllist', this.Httpus)
			
			this.getServerData(this.jiludata);
			this.listData = []
			this.listDatas = []
			this.solimit = 0;
			this.key = ''
			this.pageLoading = false;
			
			this.$nextTick(() => {
				_this.$refs.yuans.onChange(2)
			})

		},
		onShareAppMessage(res) {

			return {
				title: '搜索更多-免费小说畅读',
				path: '/pages/book_mall/index'
			}
		},
		onShareTimeline() {
			return {
				title: '阅读-免费小说畅读',
				query: '/pages/bookshelf/index',
				imageUrl: 'https://bookcover.yuewen.com/qdbimg/349573/1031777108/150.jpg'
			}
		},
		onHide(){
			this.FontFace=false
			this.$refs.popup.close();
		},
		
		methods: {
			onMessage(e) {
			    const message = e.detail;
			    if (message.from === 'web-view' && message.data.type === 'navigateBack') {
			      uni.navigateBack();
			    }
			  },
			nexturl(url){
				
				this.stops()
				uni.setStorageSync('urlxxa', url);
				
				uni.navigateTo({
					url: '/pages/about/url' 
				})
			},
			getIndex(e) {
				const {
					name
				} = this.chartData.series[e.currentIndex]

				this.key = name;
				this.searchBtn(name)
				
				this.$emit('keyWord', name)
			},
			popup(){
				this.pageLoading=false;
				this.FontFace=true
				//this.getServerData()
			},
			getServerData() {
				this.jiludata = uni.getStorageSync('jiludata') ? uni.getStorageSync('jiludata') : [];
				this.FontFace=true
				//模拟从服务器获取数据时的延时
					let arr=[]
					this.jiludata.forEach((res,index)=>{
					
						arr[index] = {};
						arr[index].name=res;
						arr[index].textSize=Math.floor(Math.random() * (30 - 20 + 1)) + 20
						
					})
					
					//模拟服务器返回数据，如果数据格式和标准格式不同，需自行按下面的格式拼接
					let res = {
						series:arr
					};
					this.chartData = JSON.parse(JSON.stringify(res));
				
			},

			flag() {
				var _this = this;
				// #ifdef  APP-PLUS
				_sql.selectSQL("select * from " + this.dbs + " where book_state=1").then(function(res) {
					_this.sqllist = res
				});
				// #endif

			},
			searchKey(event) {
				this.key = event.detail.value;
			},
			del() {
				uni.setStorageSync('jiludata', []);
				this.jiludata = []
				this.getServerData(this.jiludata)
			},
			searchBtn(dta) {
				
				
				let that = this;
				if (dta) {
					that.key = dta
				}

				if (!that.key) {
					uni.showToast({
						title: this.$t('search.qsr'),
						icon: 'none',
						duration: 2000
					});
					return;
				}
				
				if (this.jiludata.length > 0) {
					let keys = []
					this.jiludata.forEach(res => {
						if (res != that.key) {
							keys.push(res)
						}
					});
					uni.setStorageSync('jiludata', keys.concat(this.key));
				} else {
					uni.setStorageSync('jiludata', this.jiludata.concat(that.key));
				}
				this.getServerData(this.jiludata)	
				this.$refs.popup.show();
				this.FontFace=false
				this.listData = []
				this.listDatas = []
				this.pageLoading=true
				this.processAllLinks(this.sqllist);
				
				// 遍历每个分组
				
				return
				this.sqllist.forEach(res => {
					that.pageLoading = true;
					that.so(res.search_url, res)
				});
				var i = 0;


			},
			stops() {
				this.zaistop.abort();
				this.concurrencyLimit=3
				this.executingCount=0
				this.solimit = 0;
				this.linkQueue=[];
				this.pageLoading = false
				//this.key=''
			},
			// 处理链接的异步函数
			async  processLink(link) {
			  try {
			    // 发起异步请求
			    const response = await this.so(link.search_url,link);
			    // 处理返回的数据
			    console.log(response);
			  } catch (error) {
			    console.error(error);
			  }
			},
			// 添加链接到队列
			addToQueue(link) {
			  this.linkQueue.push(link);
			},
			
			// 从队列中取出链接并执行
			async  dequeueAndExecute() {
			  while (this.executingCount < this.concurrencyLimit && this.linkQueue.length > 0) {
			    const link = this.linkQueue.shift();
			    this.executingCount++;
			    this.processLink(link).finally(() => {
			      this.executingCount--;
			      this.dequeueAndExecute(); // 继续执行下一个
			    });
			  }
			},
			
			// 处理所有链接的异步函数
			async  processAllLinks(links) {
			  links.forEach(link => this.addToQueue(link));
			  await this.dequeueAndExecute();
			},

			async so(search_url, data) {
				return new Promise((resolve, reject) => {
				let that = this;
				let url = search_url.replace("{{key}}", encodeURIComponent(this.key));
				console.log('=====',url,this.pageLoading)
				let arr = {};
				if (data.search_http === 'POST') {
					let code = url.split('?')[1]
					// url=url.split('?')
					arr = this.postsplic(code)
				}
				if (!this.pageLoading) {
					return false
				}
				let header = {}
				if (data.header) {
					header = this.hesplic(data.header)
				}
				
					
					this.zaiApi({
						url: url,
						method: data.search_http,
						data: arr,
						header: header
					}).then(function(res) {
						that.solimit = that.solimit + 1;
						that.GetSearchData(res, data)
						resolve(true)
					}).catch(e => {
						reject(e);
						that.solimit = that.solimit + 1;
					});
				}); 
				 
			},
			GetSearchData(res, data) {
				let that = this;
				if (!this.pageLoading) {
					return false
				}
				_tool.searchData(res, data).then(function(res) {

					if (that.listData.length > 0) {

						that.listData = that.listData.concat(res)
					} else {
						that.listData = res
						that.listDatas = res
					}
					that.array(that.listData)
				});
			},
			array(arr) {
				

				if (this.solimit === this.sqllist.length) {

					this.stops()
				}
				let that = this;
				// 2.第一项肯定是不会重复的，我们直接将第一项存储到最终的数组中
				const output = Object.values(
					that.listData.reduce((res, o) => {
						if (!res[o.name+o.author]) {
							res[o.name+o.author] = {
								...o,
								list: []
							};
						}
						res[o.name+o.author].list.push(o);
						return res;
					}, {})
				);
				this.listDatas = output.sort((a, b) => {
					const similarityA = this.similarity(this.key, a.name);
					const similarityB = this.similarity(this.key, b.name);

					return similarityB - similarityA;
				});
			

			},
			similarity(str1, str2) {
				// 这里可以使用你自己的相似度计算方法，比如编辑距离等
				// 这里简单地比较两个字符串的相似度
				const len1 = str1.length;
				const len2 = str2.length;
				let common = 0;

				for (let i = 0; i < len1; i++) {
					for (let j = 0; j < len2; j++) {
						if (str1[i] === str2[j]) {
							common++;
							break;
						}
					}
				}

				const total = len1 + len2 - common;

				return common / total;
			},
			details(data, id) {
				//clearInterval(this.timer);
				this.popup()
				uni.setStorageSync('details' + id, data);

				uni.navigateTo({
					url: '/pages/book_mall/details?id=' + id + '&name=' + data.name + '&author=' + data.author
				})
			},
			ge() {

				uni.navigateTo({
					url: '/pages/user/yuanlist'
				})
			},
			get(url) {
				console.log('chufa', url)
				let _this = this;
				this.zaiApi({
					url: url,
				}).then((res) => {
					console.log('-----------', res)
					this.adtype=res.ad_status	
					if (res.book_source_book) {

						_this.zaiApi({
							url: res.book_source_book,
						}).then(ress => {
							uni.setStorageSync('shuyuan1', ress)
						}).catch(err => {

						});
						_this.zaiApi({
							url: res.book_source_yuan,
						}).then(ress => {
							uni.setStorageSync('shukudata', ress)
						}).catch(err => {

						});
					}
					_this.config = res;
						// 	setTimeout(() => {
						// 	//修改子组件的内容
						// 	this.$nextTick(() => {
						// 		_this.$refs.adad.update_ad()
						// 	})
						// }, 1000);
					uni.setStorageSync('config', res);

				}).catch(err => {




				});
			},
		}
	}
</script>

<style>
	.cu-bar .search-form {
		background-color: #ffffff;
		border: 13rpx solid #9E9E9E;
		line-height: 100rpx;
		height: 100rpx;
		margin: 0 10rpx 0 20rpx;
	}

	.head-hight {
		z-index: 999;
		/* 设置最大高度 */
		/* 允许垂直滚动 */
		background-color: #fff;
		height: 790rpx;
		
	}

	.cuIcon-search {
		font-size: 40rpx;
	}

	.cu-avatar.xl {
		height: 160rpx;
	}

	.jilist {
		display: flex;
		line-height: 50px;
	}

	.radius {
		height: 240rpx;
		width: 128upx;
		background-image: url('@/static/bakerBook.png');
		background-size: 100% 100%;
		background-position: 50% 50%;
		background-repeat: no-repeat;
	}

	.jilu {
		padding: 30rpx;
	}

	.sotext {
		padding: 10rpx 10rpx;
		display: inline-block;
	}

	.stop {
		display: block;
		margin-right: 20rpx;
	}

	.cu-list.menu-avatar>.cu-item {
		position: relative;
		display: flex;
		padding-right: 10upx;
		height: 240upx;
		background-color: #ffffff;
		justify-content: flex-end;
		align-items: center
	}

	.cu-list.menu-avatar>.cu-item .content {
		position: absolute;
		left: 186upx;
		width: calc(100% - 96upx - 60upx - 120upx - 20upx);
		line-height: 1.6em;
	}

	.logo {
		width: 200rpx;
		margin: auto;
		display: block;
		margin-bottom: 60rpx;
	}
	.pointer-bottom{
		padding: 30rpx;
		
	}
	.font-weght{
		font-weight: 900;
		    font-family: system-ui;
	}
	.margin-right{
		margin-right: 10rpx;
	}

</style>